package com.flame.file.service;

import java.util.List;

import com.flame.auth.core.context.AuthContextHolder;
import com.flame.core.id.IdWorker;
import com.flame.core.utils.DateUtils;
import com.flame.core.utils.FileUtils;
import com.flame.file.config.FileConfigurationProperties;
import com.flame.file.constant.FileConstants;
import com.flame.file.controller.vo.FileInfoVo;
import com.flame.file.entity.FileInfo;
import com.flame.file.mapper.FileInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * flame_sys_file_info 系统文件表
 *
 * @author 吴欣童
 * @since 2022-11-28 13:50:59
 */
@Service
public class FileInfoService {

    @Autowired
    private FileConfigurationProperties properties;

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Autowired
    private IdWorker idWorker;

    public List<FileInfo> pageFileInfo(FileInfoVo fileInfoVo) {
        return fileInfoMapper.page(fileInfoVo);
    }

    public FileInfo findById(Long fileId) {
        return fileInfoMapper.selectById(fileId);
    }

    public void deleteFileInfo(Long fileId) {
        FileInfo dbFileInfo = fileInfoMapper.selectById(fileId);
        if (dbFileInfo != null) {
            FileUtils.delete(dbFileInfo.getFileLocation());
        }
        fileInfoMapper.deleteById(fileId);
    }

    public Long save(MultipartFile file) {
        long fileId = idWorker.nextId();
        String fileFullName = file.getOriginalFilename();
        String fileName = FileUtils.getFileName(fileFullName);
        String fileType = FileUtils.getFileType(fileFullName);

        String localFilePath = FileUtils.writeFile(properties.getDir(), fileName + "-" + fileId + "." + fileType, file);

        String md5 = FileUtils.md5(localFilePath);

        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileId(fileId);
        fileInfo.setFileStorageType(FileConstants.STORAGE_TYPE_LOCAL);
        fileInfo.setFileName(fileName);
        fileInfo.setFileType(fileType);
        fileInfo.setFileLocation(localFilePath);
        fileInfo.setMd5(md5);
        fileInfo.setUploadTime(DateUtils.currentDateTime());
        fileInfo.setUploadUser(AuthContextHolder.getContext().getAccount());
        fileInfoMapper.insert(fileInfo);
        return fileId;
    }
}
